<!--
 * @Author: your name
 * @Date: 2021-07-19 10:22:47
 * @LastEditTime: 2021-07-20 14:45:34
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>哈希函数</title>
</head>
<body>
  
  <script>
    // 设计哈希函数
    // 1. 将字符串转成比较大的数字：hashCode
    // 2. 将大的数字hasCode压缩到数组范围（大小）之内
    function hashFunc(str, size) {
      // 1. 定义hashCode变量
      var hashCode = 0

      // 2. 霍纳算法，来计算hashCode的值
      // cats -> Unicode编码
      for (var i = 0; i < str.length; i ++) {
         hashCode = 37 * hashCode + str.charCodeAt(i)
      }

      // 3. 取余操作
      var index = hashCode % size

      return index
    }

    console.log(hashFunc('abc', 7)) // 4
    console.log(hashFunc('cba', 7)) // 3
    console.log(hashFunc('nba', 7)) // 5
    console.log(hashFunc('tge', 7)) // 1
    console.log(hashFunc('eee', 7)) // 0
  </script>
</body>
</html>